﻿namespace ChatGPT;


//public class SignalRHub : Hub
//{
//    private readonly IOpenAIService _openAIService;

//    private readonly IMongoRepository<ChatLog> _mongoRepository;
//    public SignalRHub(IOpenAIService openAIService
//        , IMongoRepository<ChatLog> mongoRepository)
//    {
//        _openAIService = openAIService;
//        _mongoRepository = mongoRepository;
//    }

//    //public override async Task OnConnectedAsync()
//    //{
//    //    //将同一个人的连接ID绑定到同一个分组，推送时就推送给这个分组
//    //    await Groups.AddToGroupAsync(Context.ConnectionId, user.Account);
//    //}

//    /// <summary>
//    /// 
//    /// </summary>
//    /// <param name="input"></param>
//    /// <returns></returns>
//    public async Task Query(string input)
//    {
//        string userId = "123";
//        var filter = Builders<ChatLog>.Filter.Eq(x => x.UserId, userId);
//        var sort = Builders<ChatLog>.Sort.Descending(x => x.CreateTime);
//        var content = _mongoRepository.Find(filter, sort).Select(x => new ChatMessage(x.Role, x.Content)).ToList();
//        content.Add(new ChatMessage("user", input));
//        await _mongoRepository.AddAsync(new ChatLog { UserId = userId, Role = "user", Content = input,CreateTime = DateTime.Now});

//        Console.WriteLine($"收到提问：{input}");
//        var completions = _openAIService.ChatCompletion.CreateCompletionAsStream(new()
//        {
//            Messages = content
//        }, Models.ChatGpt3_5Turbo);

//        await Clients.Client(Context.ConnectionId).SendAsync("StartConnect", "开始");
//        StringBuilder sb = new();
//        await foreach (var completionResponse in completions)
//        {
//            if (completionResponse.Successful)
//            {
//                var message = completionResponse.Choices[0].Message.Content;
//                if (string.IsNullOrEmpty(message))
//                    continue;
//                sb.Append(message);
//                await Clients.Client(Context.ConnectionId).SendAsync("KeepConnect", message);
//            }
//            else
//            {
//                if (completionResponse.Error != null)
//                {
//                    await Clients.Client(Context.ConnectionId).SendAsync("KeepConnect", completionResponse.Error.Message);
//                }
//                else
//                {
//                    await Clients.Client(Context.ConnectionId).SendAsync("KeepConnect", "<unknow>");
//                }
//            }
//        }
//        await Clients.Client(Context.ConnectionId).SendAsync("EndConnect", "结束");
//        await _mongoRepository.AddAsync(new ChatLog { UserId = userId,Role = "assistant", Content = sb.ToString(),CreateTime = DateTime.Now });
//    }
//}